package com.chaoyi.util.oss;

import java.io.InputStream;

import javax.servlet.http.Part;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;

/**
 * 对OSS服务器进行上传删除等的处理
 * 
 * @ClassName: OSSManageUtil
 * @Description:
 * @author liujh
 * @date 2015-3-26 上午10:47:00
 * 
 */
public class ApkOSSManageUtil {

	/**
	 * 上传Apk安卓程序安装包至OSS服务器文件 @Title: uploadFile @Description: @param @param
	 * ossConfigure @param @param file @param @param
	 * remotePath @param @return @param @throws Exception 设定文件 @return String
	 * 返回类型 @throws
	 */
	/**
	 * ApkOSSConfigure 必要参数
	 * FileItem 上传文件流
	 * path文件保存路径
	 * fileName 文件名称
	 */
	public static String uploadFile(ApkOSSConfigure ossConfigure, Part anchorHeadImgFile,String path,String fileName) throws Exception {
		InputStream fileContent = null;
		fileContent = anchorHeadImgFile.getInputStream();

		OSSClient ossClient = new OSSClient(ossConfigure.getEndpoint(), ossConfigure.getAccessKeyId(),
				ossConfigure.getAccessKeySecret());

		// 创建上传Object的Metadata
		ObjectMetadata objectMetadata = new ObjectMetadata();
		objectMetadata.setContentLength(anchorHeadImgFile.getSize());
		objectMetadata.setCacheControl("max-age=86400");
		objectMetadata.setHeader("Pragma", "max-age=86400");
		objectMetadata.setContentType(contentType(anchorHeadImgFile.getSubmittedFileName().substring(anchorHeadImgFile.getSubmittedFileName().lastIndexOf("."))));
		objectMetadata.setContentDisposition("inline;filename=" + fileName);

		// 执行 put 请求（上传文件），并且返回对象的MD5摘要
		ossClient.putObject(ossConfigure.getBucketName(), path+fileName, fileContent, objectMetadata);
//		System.out.println(ossConfigure.getAccessUrl() + "/" + path+fileName);
		return ossConfigure.getAccessUrl() + "/" + path +fileName;
	}
	
	/**
	 * 根据key删除OSS服务器上的文件 @Title: deleteFile @Description: @param @param
	 * ossConfigure @param @param filePath 设定文件 @return void 返回类型 @throws
	 */
	public static void deleteFile(ApkOSSConfigure ossConfigure, String filePath) {
		OSSClient ossClient = new OSSClient(ossConfigure.getEndpoint(), ossConfigure.getAccessKeyId(),
				ossConfigure.getAccessKeySecret());
		ossClient.deleteObject(ossConfigure.getBucketName(), parseRelatePath(filePath));

	}
	
	public static String parseRelatePath(String path){
		int index = path.indexOf("://");
		if(index!=-1){
			index += 4;
			int i = path.indexOf("/",index);
			if(i!=-1)
				path = path.substring(i+1);
			else
				path = path.substring(index);
		}
		return path;
	}

	/**
	 * Description: 判断OSS服务文件上传时文件的contentType @Version1.0
	 * 
	 * @param FilenameExtension
	 *            文件后缀
	 * @return String
	 */
	public static String contentType(String FilenameExtension) {
		return "application/vnd.android.package-archive";
	}
}